package com.polaris.live.ui.main.live

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.polaris.live.R
import com.polaris.live.adapter.HomeUserHeadAdapter
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentRoomMeBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.PartyRoomResp
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.HomeHeadItemDecoration
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.me.RoomMeViewModel
import com.polaris.live.widget.country.countryIcons

/**
 * RoomMeFragment
 *
 * @author Created by 半仙 on 2024/9/20/020 10:05
 */
class RoomMeFragment : BaseVbFragment<RoomMeViewModel, FragmentRoomMeBinding>(), OnAutoRefreshListener {

    private var partyRoomResp: PartyRoomResp? = null

    private val mFragments = mutableListOf<Fragment>()

    override fun initView(savedInstanceState: Bundle?) {
        changePage(0)
        initObserver()
        initListener()
        mFragments.add(FriendRoomFragment().apply {
            arguments = bundleOf("type" to FriendRoomFragment.NEARBY)
        })
        mFragments.add(FriendRoomFragment().apply {
            arguments = bundleOf("type" to FriendRoomFragment.JOINED)
        })
        mBinding.vpList.adapter = ViewPagerAdapter(mFragments, this)
        mBinding.vpList.offscreenPageLimit = mFragments.size
    }

    private fun initListener() {
        mBinding.tvRecent.setOnSingleClickListener {
            mBinding.vpList.currentItem = 0
            changePage(0)
        }
        mBinding.tvJoined.setOnSingleClickListener {
            mBinding.vpList.currentItem = 1
            changePage(1)
        }
        mBinding.vpList.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                changePage(position)
            }
        })
        mBinding.consRoom.setOnSingleClickListener {
            val liveType = UserManager.getUser().live?.liveType
            StartLiveProxy.builder(this)
                .recoverLive(mViewModel, liveType, partyRoomResp?.roomId)
        }
        mBinding.consCreate.setOnSingleClickListener {
            GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                //开启派对
                Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                    .navigation(requireActivity())
            })
        }
        mBinding.ivStartParty.setOnSingleClickListener {
            LiveUtils.openPartyChecking(requireContext(), mViewModel)
        }
    }

    private fun changePage(position: Int) {
        when (position) {
            0 -> {
                mBinding.tvRecent.isSelected = true
                mBinding.tvJoined.isSelected = false
                mBinding.tvRecent.setBackgroundResource(R.drawable.friend_ship_tab_select_back)
                mBinding.tvJoined.setBackgroundResource(R.drawable.friend_ship_tab_not_select_back)
            }

            1 -> {
                mBinding.tvRecent.isSelected = false
                mBinding.tvJoined.isSelected = true
                mBinding.tvJoined.setBackgroundResource(R.drawable.friend_ship_tab_select_back)
                mBinding.tvRecent.setBackgroundResource(R.drawable.friend_ship_tab_not_select_back)
            }
        }

    }

    private fun initObserver() {
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                partyRoomResp = it
                if (it.roomId?.isNotEmpty() == true) {
                    mBinding.consRoom.visibility = View.VISIBLE
                    mBinding.consCreate.visibility = View.GONE
                    Glide.with(requireContext()).load(ImageUtils.imgPath(it.roomCover))
                        .transform(CenterCrop(), RoundedCorners(8.autoDp)).into(mBinding.ivUserCover)
                    mBinding.tvNickName.text = it.roomName
                    mBinding.vipView.setVipLevel(UserManager.getUser().profile?.vipLevel)
                    mBinding.roomFrame.setRoomFrame(it.roomFrame)
                    if (CommonUtils.isMan(UserManager.getUser().sex)) {
                        mBinding.widgetLevel.setRichsLevel(UserManager.getUser().account?.richs ?: 0)
                    } else {
                        mBinding.widgetLevel.setCharmsLevel(UserManager.getUser().account?.charms ?: 0)
                    }
                    mBinding.tvNum.text = "${it.joinUser}"
                    mBinding.tvUserDetail.text = it.welcomeSpeech ?: " "
                    mBinding.headRecycler.apply {
                        adapter = HomeUserHeadAdapter().apply { setList(it.siteUsers?.asReversed()) }
                        layoutManager =
                            LinearLayoutManager(mBinding.root.context, LinearLayoutManager.HORIZONTAL, false).apply {
                                reverseLayout = true
                                stackFromEnd = true
                            }
                        itemAnimator = null
                        addItemDecoration(HomeHeadItemDecoration())
                    }
                    val profile = UserManager.getUser().profile
                    if (profile?.secondCountryHidden.toBoolean()) {
                        mBinding.llCountryBottom.visibility = View.GONE
                    } else {
                        val country = profile?.secondCountry
                        if (country != null) {
                            val countryIcon = countryIcons[country]
                            if (countryIcon != null) {
                                mBinding.llCountryBottom.visibility = View.VISIBLE
                                mBinding.itemRoomCountry.setImageResource(countryIcon)
                            }
                        }
                    }
                } else {
                    mBinding.consRoom.visibility = View.GONE
                    mBinding.consCreate.visibility = View.VISIBLE
                    mBinding.consRoom.visibility = View.GONE
                }
            })
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mViewModel.getPartyRoom()
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getPartyRoom()
    }

    override fun onAutoRefresh() {
        if (isCreated()) {
            mViewModel.getPartyRoom()
            val fragment = mFragments.getOrNull(mBinding.vpList.currentItem) ?: return
            if (fragment is OnAutoRefreshListener) {
                fragment.onAutoRefresh()
            }
        }
    }
}